package com.lej.push.service

import android.content.Context
import android.content.Intent
import android.util.Log
import com.igexin.sdk.GTIntentService
import com.igexin.sdk.message.GTCmdMessage
import com.igexin.sdk.message.GTNotificationMessage
import com.igexin.sdk.message.GTTransmitMessage
import com.lej.core.base.app
import com.lej.core.common.*
import com.lej.core.utils.MMKVUtils
import com.lej.core.utils.extention.fromJson
import com.lej.core.utils.extention.logI
import com.lej.core.utils.extention.safe
import com.lej.dataservice.club.bean.push.PushPayloadInfo
import com.lej.dataservice.club.provider.IPushDispatchProvider
import com.lej.push.PushUtils
import com.lej.push.notification.NotificationUtils

class GTPushIntentServices : GTIntentService() {

    override fun onReceiveServicePid(context: Context, pid: Int) {
        Log.e("sss", "onReceiveServicePid")
    }

    // 处理透传消息
    override fun onReceiveMessageData(context: Context, msg: GTTransmitMessage) {
        // 透传消息的处理方式，详看SDK demo
        Log.e("sss", "onReceiveMessageData")
        "收到透传推送".logI(LogTags.push)

        val payloads = msg.payload ?: return
        val msgContent = String(payloads)
        val pushInfo = msgContent.fromJson<PushPayloadInfo>()

        pushInfo.toString().logI(LogTags.push)

        pushInfo?.let {
            val intent = Intent(app, Class.forName("com.lej.club.ui.PushDispatcherActivity")).apply {
                putExtra("payload",msgContent)
            }
            NotificationUtils.notify(pushInfo.msg.safe(),pushInfo.photoid.hashCode(), intent)
        }
    }

    // 接收 cid
    override fun onReceiveClientId(context: Context, cid: String) {
        Log.e("sss", "onReceiveClientId -> cid = $cid")
        PCacheInfo.clientId = cid//保存cid
        if (PushUtils.shouldBindClientId) PushUtils.bindCid()
    }

    // cid 离线上线通知
    override fun onReceiveOnlineState(context: Context, online: Boolean) {
        Log.e("sss", "onReceiveOnlineState:${online}")
    }

    // 各种事件处理回执
    override fun onReceiveCommandResult(context: Context, cmdMessage: GTCmdMessage) {
        Log.e("sss", "onReceiveCommandResult")
    }

    // 通知到达，只有个推通道下发的通知会回调此方法
    override fun onNotificationMessageArrived(context: Context, msg: GTNotificationMessage) {
        Log.e("sss", "onNotificationMessageArrived")
        msg.content.logI(LogTags.push)
    }

    // 通知点击，只有个推通道下发的通知会回调此方法
    override fun onNotificationMessageClicked(context: Context, msg: GTNotificationMessage) {
        Log.e("sss", "onNotificationMessageClicked")
        msg.content.logI(LogTags.push)
        val msgContent = msg.content ?: return
        val pushInfo = msgContent.fromJson<PushPayloadInfo>()

        IPushDispatchProvider.instance?.dispatchPayload(payload = pushInfo)
        pushInfo.toString().logI(LogTags.push)
    }
}
